package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"

	"gitee.com/bluesky2006/alarm/dao"
	"gitee.com/bluesky2006/alarm/service"
	"gitee.com/bluesky2006/alarm/setting"
	"github.com/alfred-zhong/wserver"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage：./alarm conf/config.ini")
		return
	}
	fmt.Println("start init database--------------")
	// 加载配置文件
	if err := setting.Init(os.Args[1]); err != nil {
		fmt.Printf("load config from file failed, err:%v\n", err)
		return
	}
	// 创建数据库
	// sql: CREATE DATABASE alarm;
	// 连接数据库
	err := dao.InitMySQL(setting.Conf.MySQLConfig)
	if err != nil {
		fmt.Printf("init mysql failed, err:%v\n", err)
		return
	}
	defer dao.Close() // 程序退出关闭数据库连接

	fmt.Println("start websocket server--------------")
	startWebSocket()

}

func startWebSocket() {
	port := fmt.Sprintf(":%d", setting.Conf.Port)
	server := wserver.NewServer(port)
	server.LoopInterval = setting.Conf.Interval
	// Define websocket connect url, default "/ws"
	server.WSPath = "/ws"
	// Define push message url, default "/push"
	server.PushPath = "/push"

	// Set AuthToken func to authorize websocket connection, token is sent by
	// client for registe.
	server.AuthToken = func(token string) (userID string, ok bool) {
		// TODO: check if token is valid and calculate userID
		if token == "aaa" {
			return "jack", true
		}
		if token == "bbb" {
			return "vincentzou", true
		}
		return "", false
	}

	// Set PushAuth func to check push request. If the request is valid, returns
	// true. Otherwise return false and request will be ignored.
	server.PushAuth = func(r *http.Request) bool {
		// TODO: check if request is valid

		return true
	}
	server.StatusAuth = func(r *http.Request) bool {
		// TODO: check if request is valid

		return true
	}

	server.PushMethod = func(params map[string]string) ([]byte, error) {
		fmt.Println("PushMethod-----------------", params)
		list, err := service.LoadActiveAlarmRecords(params)
		//	fmt.Printf("--push method--%#v", list)
		b, err := json.Marshal(list)
		if err != nil {
			fmt.Printf("json.Marshal failed, err:%v\n", err)
			return nil, err
		}
		//str := fmt.Sprintf("%s", b)
		//fmt.Println("-->", str)
		return b, err
	}

	// Run server
	if err := server.ListenAndServe(); err != nil {
		panic(err)
	}
}
